<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html >
<html lang="zh-CN">
  <head>
    
    <title>测试编辑</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	 <script type="text/javascript" src="${pageContext.servletContext.contextPath}/js/jtopo-min.js"></script>
	 <script type="text/javascript" src="${pageContext.servletContext.contextPath}/js/toolbar.js"></script>
     <script type="text/javascript" src="${pageContext.servletContext.contextPath}/js/jquery.js"></script>
     <!-- 新 Bootstrap 核心 CSS 文件 -->
	<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
	 <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
	<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
     <style type="text/css">
     		
	.contextmenu {
		border: 1px solid #aaa;
		border-bottom: 0;
		background: #eee;
		position: absolute;
		list-style:none;
		margin: 0;
		padding: 0;
		display: none;
	}
																			   
	.contextmenu li a {
		display: block;
		padding: 10px;
		border-bottom: 1px solid #aaa;
		cursor: pointer;
	}
																			   
	.contextmenu li a:hover {
		background: #fff;
	}
	
     
     </style>
  
  </head>
  
  <body>
 
    <div id="candiv" style="padding-top: 3%;" >
      <select id="lx" class="btn">
      		<option value="fwq" >服务器</option>
      		<option value="jhj" >交换机</option>		
      		<option value="fhq" >防火墙</option>
      </select>
      
      	<ul id="contextmenu" class="contextmenu" style="display:none;">	
			<li><a>顺时针旋转</a></li>
			<li><a>逆时针旋转</a></li>	
			<li><a>更改颜色</a></li>
			<li><a>放大</a></li>
			<li><a>缩小</a></li>	
			<li><a>删除该节点</a></li>
		    </ul>
		    
		 <ul id="link" class="contextmenu" style="display:none;">	
			<li><a>删除</a></li>
		    </ul>   
        <button onclick="addNode()" class="btn">新增</button>
        <button onclick="addlabel()" class="btn">添加标签</button>
        <button style="margin-left: 60%;" onclick="saveObj()" class="btn">保存</button>
        <button onclick="saveLabel()" class="btn"> 保存标签</button>
        <button onclick="getselect()" class="btn">删除连线</button>
      <!--   <button onclick="saveObj()">保存对象</button> -->
       <%--  <a href="${ }"></a> --%>
    <canvas id="canvas" width="1400" height="790" style="border: 1px solid rgb(68, 68, 68); cursor: default; background-color: rgb(238, 238, 238);">
     </canvas>   
   </div>
  
    <script type="text/javascript">
    
    
      /**
               节点对象
      */
      var nodeObj={uuid:"", type:"",x:"",y:"",w:"",h:"",text:"" ,src:""};
   	 //节点集合   
      var nodeArray=new Array();
    
   	var canvas = document.getElementById('canvas');	
   	  		
			var stage = new JTopo.Stage(canvas);
			showJTopoToobar(stage);
			var scene = new JTopo.Scene(stage);
			scene.background = './img/bg.jpg';
			var beginNode = null;
			var tempNodeA = new JTopo.Node('tempA');;
			tempNodeA.setSize(1, 1);
			
			var tempNodeZ = new JTopo.Node('tempZ');;
			tempNodeZ.setSize(1, 1);
			
			var link = new JTopo.Link(tempNodeA, tempNodeZ);
			
			var menuNode="";
		
		
			
			scene.mouseup(function(e){
			  	//判断节点是否实现了node这个类 //菜单删除功能
				if(e.target != null && e.target instanceof JTopo.Node){
				menuNode=e.target;
				menuNode.addEventListener('mouseup', function(event){
				currentNode = this;
				handler(event);
			});
			} 	
			//判断是否右键点击
			if(e.which!=3){
				if(e.button == 2){
					scene.remove(link);
					return;
				}
				//判断事件源是否是node的子类
				if(e.target != null && e.target instanceof JTopo.Node){
				    //如果起始节点不等于空
					if(beginNode == null){
					  //将事件源作为起始节点
						beginNode = e.target;
						scene.add(link);
						tempNodeA.setLocation(e.x, e.y);
						tempNodeZ.setLocation(e.x, e.y);
					}else if(beginNode !== e.target){
					//debugger;
					//清空对象
					nodeObj={uuid:"",type:"",x:"",y:"",w:"",h:"",text:"" ,src:""};
				/* 	var uid=uuid(); */
						var endNode = e.target;
						var l = new  JTopo.FoldLink(beginNode, endNode);
						scene.add(l);
						beginNode = null;
						scene.remove(link);
						
					}else{
						beginNode = null;
					}
				}else{
					scene.remove(link);
				}
			  //如果已经点击节点则beginnode不为空
				if(beginNode!=null&&beginNode!=e.target){
				  	scene.add(link);
				   tempNodeA.setLocation(e.x, e.y);
					tempNodeZ.setLocation(e.x, e.y);
				 var node=new JTopo.Node();
				   node.setBound(e.x, e.y,0,0);
				   	var l = new  JTopo.FoldLink(beginNode, node);
					scene.add(l);
				
						beginNode=node;
				  }
			}else{
			 beginNode=null;
			}
			});
			
			var delLink="";
			
			scene.mousedown(function(e){
			  
				if(e.target == null || e.target === beginNode || e.target === link){
					scene.remove(link);
				}
			     if(e.which==2){
			      beginNode=null;
			     }
			     
			     if(e.target !=null && e.target instanceof JTopo.Link){
			     	delLink=e.target;
			     }
			     
			});

			scene.mousemove(function(e){
				tempNodeZ.setLocation(e.x, e.y);
			});
			
			//双击事件 逻辑
			scene.dbclick(function(event){
			//添加一个输入框 为绝对布局
			var textfield =$("<textarea  style='position:absolute;width: 70px;display:none;' onblur=editing(this) ></textarea>");
			$("#candiv").append(textfield);
			   //如果事件源为空则直接退出
				if(event.target == null) return;
				//获取事件源
				var e = event.target;
				textfield.css({
				display:'',
				 //绝对布局坐标x,y
				  top: event.pageY,
				  left: event.pageX - e.width/2
				}).show().attr('value', e.text).focus().select();
				
				textfield.value= e;
				//将事件源的文字设置为空
				e.text = "";
				//创建全局变量
				test=e;
			});
			
			
			
			function editing(edit){
			    //设置节点的文字
				test.text=$(edit).val();
				//移除元素
				$(edit).remove();
				//$(edit).css('display','none');
			}
		//添加新节点
		function addNode(){
		
		var node=new JTopo.Node();
		var lx= $("#lx").val();
		if(lx=="fwq"){
		     node.setBound(50,100,50,55);
		     node.setImage('./img/Home_Server.png');
		     node.innerText="./img/Home_Server.png";
		   scene.add(node);
		}else if(lx=="fhq"){
		    node.setBound(50, 50,50, 55);
		    node.setImage('./img/firewall.png');
		     node.innerText="./img/firewall.png";
			scene.add(node);
		}else if(lx=="jhj"){
			 node.setBound(50, 50,50, 55);
			  node.innerText="./img/msr.png";
		    node.setImage('./img/msr.png');
			scene.add(node);
		}
		}
	/* 	function save(){
		console.log(stage.toJson());
	    console.log(scene.getDisplayedElements());
		  var saveStr=JSON.stringify(nodeArray);
		  $.ajax({
		  	url:"${pageContext.servletContext.contextPath}/savenode",
		  	contentType:"application/json",
		     type:"post",
		     data:saveStr,
		     success:function(data){
		     console.log(data);
		     }
		  });
		}
	 */
		//保存当前页面对象
	    function saveObj(){
	       //获取到页面当前所有对象
			var sceneObj=scene.getDisplayedElements();
			var linkArray=new Array();//保存所有线对象
				var anyObj=new Array();//用来保存所有的linkNodeObj
	      for(var i=0;i<sceneObj.length;i++){
	      	 //判断对象是不是线 如果是就保存到LinkArray
	      	 if(sceneObj[i].elementType=="link"){
	      	 linkArray.push(sceneObj[i]);
	      	 }
	      }
	       //取出线之间的两个节点
	       for(var i=0;i<linkArray.length;i++){
	       		nodeObj=null;//清空对象
	      var linkNodeObj=new Array();//用来存线之间的两个节点 ;
				nodeObj={uuid:"",type:"",x:"",y:"",w:"",h:"",text:"" ,src:""};
	       		nodeObj.x=linkArray[i].nodeA.x;
	       		nodeObj.y=linkArray[i].nodeA.y;
	       		nodeObj.w=linkArray[i].nodeA.width;
	       		nodeObj.h=linkArray[i].nodeA.height;
	       		nodeObj.src=linkArray[i].nodeA.innerText;
	       		nodeObj.text=linkArray[i].nodeA.text;
	       		linkNodeObj.push(nodeObj);
	       		nodeObj=null;//清空对象
	       		nodeObj={uuid:"",type:"",x:"",y:"",w:"",h:"",text:"" ,src:""};
	       		nodeObj.x=linkArray[i].nodeZ.x;
	       		nodeObj.y=linkArray[i].nodeZ.y;
	       		nodeObj.w=linkArray[i].nodeZ.width;
	       		nodeObj.h=linkArray[i].nodeZ.height;
	       		nodeObj.src=linkArray[i].nodeZ.innerText;
	       		nodeObj.text=linkArray[i].nodeZ.text;
	       		linkNodeObj.push(nodeObj);
	       		anyObj.push(linkNodeObj);//将两个节点集合添加进去
	       }
	       var anyStr=JSON.stringify(anyObj);
	      
	       $.ajax({
	     	url:"${pageContext.servletContext.contextPath}/saveObj",
		  	contentType:"application/json",
		     type:"post",
		     data:anyStr,
		     success:function(data){
		     console.log(data);
		     }
	       });
	       
		}
			function handler(event){
				if(event.button == 2){// 右键
					// 当前位置弹出菜单（div）
					$("#contextmenu").css({
						top: event.pageY,
						left: event.pageX
					}).show();	
				}
			}
			
			
			stage.click(function(event){
				if(event.button == 0){// 右键
					// 关闭弹出菜单（div）
					$("#link").hide();
				}
			});
						
			
		
			/* 右键菜单处理 */	
			$("#contextmenu a").click(function(){
				var text = $(this).text();
				if(text == '删除该节点'){
					scene.remove(currentNode);
					currentNode = null;
				}if(text == '撤销上一次操作'){
					currentNode.restore();
				}else{
					//currentNode.save();
				}
				
				if(text == '更改颜色'){
					currentNode.fillColor = JTopo.util.randomColor();
				}else if(text == '顺时针旋转'){
					currentNode.rotate += 0.5;
				}else if(text == '逆时针旋转'){
					currentNode.rotate -= 0.5;
				}else if(text == '放大'){
					currentNode.scaleX += 0.2;
					currentNode.scaleY += 0.2;
				}else if(text == '缩小'){
					currentNode.scaleX -= 0.2;
					currentNode.scaleY -= 0.2;
				}
				$("#contextmenu").hide();
			}
			
			);
			
			function linkhandler(event){
				if(event.button == 2){// 右键
					// 当前位置弹出菜单（div）
					$("#contextmenu").css({
						top: event.pageY,
						left: event.pageX
					}).show();	
				}
			}
			
			
			stage.click(function(event){
				if(event.button == 0){// 右键
					// 关闭弹出菜单（div）
					$("#contextmenu").hide();
				}
			});
			
			
			function addlabel(){
			    // 不指定布局的时候，容器的布局为自动(容器边界随元素变化）
            var container = new JTopo.Container('');
            container.dragble=false;
            container.textPosition = 'Middle_Center';
            container.x=100;
            container.y=100;
            container.width=150;
             container.height=40;
            container.fontColor = '255,255,255';
            container.font = '18pt 微软雅黑';
            container.fillColor = '238,238,238';
            container.borderRadius = 20; // 圆角
            console.log(container);
            scene.add(container);
			}			
			var containerArray=new Array();//标签集合
			function saveLabel(){
	       var  sceneObj2=scene.getDisplayedElements();
		   for(var i=0;i<sceneObj2.length;i++){
	      	 //判断对象是不是线 如果是就保存到LinkArray
	      	 if(sceneObj2[i].elementType=="container"){
	      	 containerArray.push(sceneObj2[i]);
	      	 }
	      }
	      var containArray=new Array();//存标签集合
	      for(var i=0;i<containerArray.length;i++){
	      		nodeObj=null;
	      		nodeObj={uuid:"",type:"",x:"",y:"",w:"",h:"",text:"" ,src:""};
	       		nodeObj.x=containerArray[i].x;
	       		nodeObj.y=containerArray[i].y;
	       		nodeObj.text=containerArray[i].text;
	       		containArray.push(nodeObj);
	      }
	       var labelJSON=JSON.stringify(containArray);
			$.ajax({
			url:'${pageContext.servletContext.contextPath}/saveLabel',
			contentType:'application/json',
			type:'post',
			data:labelJSON,
			success:function(){
			}
			
			
			});
			}
		 
			
		function getselect(){
		  scene.remove(delLink);
		  var modeA=delLink.nodeA;
		  if(typeof(modeA.text)=="undefined"||modeA.text==""){
		  scene.remove(modeA);
		  }
		  var modeZ=delLink.nodeZ;
		  console.log(modeZ);
		  if(typeof(modeZ.text)=="undefined"||modeZ.text==""){
		  scene.remove(modeZ);
		  }
		}
		function uuid() {
	    var s = [];
	    var hexDigits = "0123456789abcdef";
	    for (var i = 0; i < 36; i++) {
	        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	    }
	    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
	    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
	    s[8] = s[13] = s[18] = s[23] = "-";
	 
	    var uuid = s.join("");
	    return uuid;
	}
    </script>
    
  </body>
</html>
